﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Autofac;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using RawInput_dll;
using ZnakovMD;

namespace ComputerVision
{
    public partial class frmXeVaoXeRa : frmObject
    {
        private readonly RawInput _rawinput;
        private IService<ConfigrationCamera> _configCamera;
        private IService<LoaiXe> _loaiXe;
        private IService<XeTemp> _xeT;
        private IService<Xe> _xe;
        private IService<VeXe> _veXe;
        private VeXe _veXe2;
        private XeTemp _xe2;
        private XeTemp _xe3;
        private XeTemp _xe4;
        private XeTemp _modelV = null;
        private Xe _modelR = null;
        private string oldCard = string.Empty;

        private string _computerName;

        private Bitmap imgT = null;
        private Bitmap imgS = null;
        private Random rand;
        private string _veXeDap;
        private string cardNumberVao = string.Empty;
        private string cardNumberRa = string.Empty;
        private bool isCardReaderVao = false;
        private bool isCardReaderRa = false;
        private bool readOk = false;
        private bool userType = false;
        private string tempNumber = string.Empty;
        private string readerDevideVao = string.Empty;
        private string readerDevideRa = string.Empty;

        private string tempFile = string.Empty;
        private ImgageArrayVao imageArrayVao;
        private ImgageArrayRa imageArrayRa;
        private FileUtil fileUtil;
        private int countVT = 0;
        private int countVS = 0;
        private int countRT = 0;
        private int countRS = 0;
        private string cardStatusVao = string.Empty;
        private string cardStatusRa = string.Empty;
        private string _veTempVao = string.Empty;
        private string _veTempRa = string.Empty;
        private int autoCountRa = 0;
        private int autoCountVao = 0;
        private bool isValidCard = true;

        IZnakov lpr;
        private IProcessor proc;
        List<Candidate> cds;

        public frmXeVaoXeRa()
        {
            InitializeComponent();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            _rawinput = new RawInput(Handle);
            _rawinput.CaptureOnlyIfTopMostWindow = true;    // Otherwise default behavior is to capture always
            _rawinput.AddMessageFilter();                   // Adding a message filter will cause keypresses to be handled
            _rawinput.KeyPressed += OnKeyPressed;

            _computerName = Environment.MachineName;
            _configCamera = Program.Container.Resolve<IService<ConfigrationCamera>>();
            _loaiXe = Program.Container.Resolve<IService<LoaiXe>>();
            _xe = Program.Container.Resolve<IService<Xe>>();
            _xeT = Program.Container.Resolve<IService<XeTemp>>();
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            //_process = new ImageProcess();
            //_soVe = txtSoVe.Text;
            this.ActiveControl = txtSoTheVao;
            LoadLoaiXeRa();
            LoadLoaiXeVao();

            fileUtil = new FileUtil();
            lpr = Znakov.Setup();
            //read license
            lpr.set_productKey(Encoding.UTF8.GetBytes(Utilities.Dec(Constants.Map)));
            lpr.set_countryWeight("Vietnam", 1.0f);
            lpr.realizeCountryWeights();
            proc = lpr.createProcessor();

            //Xe vao
            axLiveVaoTruoc.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveVaoTruoc_OnGetPicture);
            axLiveVaoSau.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveVaoSau_OnGetPicture);

            //Xe ra
            axLiveRaTruoc.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveRaTruoc_OnGetPicture);
            axLiveRaSau.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveRaSau_OnGetPicture);

        }

        void axLiveVaoTruoc_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countVT == 1)
            {
                return;
            }

            axLiveVaoSau.StartGrapImage(true);
            countVS = 0;
            this.imageArrayVao = new ImgageArrayVao(tempFile, fileUtil.tempFolderToday);

            countVT = 1;
            axLiveVaoTruoc.StartGrapImage(false);
            picVaoTruoc.Image = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            //picVaoTruoc.Image = imgT;

            if (!fileUtil.WriteImage(picVaoTruoc.Image, imageArrayVao.NameTruoc, "V"))
            {
                AlertList.Error("Không ghi được ảnh chụp từ camera trước. Vui lòng thử lại.");
            }
        }

        void axLiveVaoSau_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countVS == 1)
            {
                return;
            }
            countVS = 1;
            axLiveVaoSau.StartGrapImage(false);
            picVaoSau.Image = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            //_img1End = imgS;
            //picVaoSau.Image = imgS;

            if (fileUtil.WriteImage(picVaoSau.Image, imageArrayVao.NameSau, "V"))
            {
                //wroteImage2 = true;

                ValidCardVao();
                if (cardStatusVao == string.Empty)
                {
                    var loaiXe = cbLoaiXeVao.SelectedItem as LoaiXe;
                    _modelV = new XeTemp()
                    {
                        Id = Guid.NewGuid(),
                        LoaiXeId = loaiXe.Id,
                        SoVe = txtSoTheVao.Text.Trim(),
                        BienSoXe = txtBienSoVao.Text.ToUpper(),
                        NgayVao = DateTime.Now,
                        GiaTien = loaiXe.GiaTien,
                        //ImgBienXeVao = this.imageArray.NameBienSoUrl,
                        ImgVaoTruoc = this.imageArrayVao.NameTruocUrl,
                        ImgVaoSau = this.imageArrayVao.NameSauUrl,
                        Status = (!userType),
                        Created = DateTime.Now,
                        CreatedBy = Constants.CurrentUser,
                        Modified = DateTime.Now,
                        ModifiedBy = Constants.CurrentUser
                    };
                }

            }
            else
            {
                //wroteImage2 = false;
                AlertList.Error("Không ghi được ảnh chụp từ camera sau. Vui lòng thử lại...");
            }

            //Timer_Vao.Enabled = true;
            if (picVaoSau.Image != null)
            {
                cds = proc.analyze((Bitmap)picVaoSau.Image, 120);
                if (cds.Count > 0)
                {
                    foreach (Candidate cd in cds)
                    {
                        txtBienSoVao.Text = cd.text;
                    }
                }
                else
                    txtBienSoVao.Text = "";
            }

            autoCountVao = 0;

        }

        void axLiveRaTruoc_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countRT == 1)
            {
                return;
            }
            axLiveRaSau.StartGrapImage(true);
            countRS = 0;
            this.imageArrayRa = new ImgageArrayRa(tempFile, fileUtil.tempFolderToday);

            axLiveRaTruoc.StartGrapImage(false);
            picRaTruoc.Image = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            //picRaTruoc.Image = imgT;
            countRT = 1;

            if (!fileUtil.WriteImage(picRaTruoc.Image, imageArrayRa.NameTruoc, "R"))
            {
                AlertList.Error("Không ghi được ảnh chụp từ camera trước. Vui lòng thử lại.");
            }
        }

        void axLiveRaSau_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countRS == 1)
            {
                return;
            }
            axLiveRaSau.StartGrapImage(false);
            picRaSau.Image = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            //img3end = imgS;
            //picRaSau.Image = imgS;
            countRS = 1;

            if (fileUtil.WriteImage(picRaSau.Image, imageArrayRa.NameSau, "R"))
            {
                if (cardStatusRa == string.Empty)
                {
                    _modelR = new Xe()
                    {
                        Id = Guid.NewGuid(),
                        LoaiXeId = _xe3.LoaiXeId,
                        SoVe = _xe3.SoVe,
                        BienSoXe = _xe3.BienSoXe,
                        NgayVao = _xe3.NgayVao,
                        NgayRa = DateTime.Now,
                        GiaTien = _xe3.GiaTien,
                        ImgBienXeVao = _xe3.ImgBienXeVao,
                        ImgVaoTruoc = _xe3.ImgVaoTruoc,
                        ImgVaoSau = _xe3.ImgVaoSau,
                        //ImgBienXeRa = this.imageArray.NameBienSoUrl,
                        ImgRaTruoc = this.imageArrayRa.NameTruocUrl,
                        ImgRaSau = this.imageArrayRa.NameSauUrl,
                        Status = _xe3.Status,
                        Created = _xe3.Created,
                        CreatedBy = _xe3.CreatedBy,
                        Modified = DateTime.Now,
                        ModifiedBy = Constants.CurrentUser
                    };
                }

            }
            else
            {
                AlertList.Error("Không ghi được ảnh chụp từ camera sau. Vui lòng thử lại...");
            }

            //Timer_Ra.Enabled = true;
            if (picRaSau.Image != null)
            {
                cds = proc.analyze((Bitmap)picRaSau.Image, 120);
                if (cds.Count > 0)
                {
                    foreach (Candidate cd in cds)
                    {
                        txtBienSoRaRa.Text = cd.text;
                    }
                }
                else
                    txtBienSoRaRa.Text = "";
            }
            autoCountRa = 0;
        }

        private void frmXeVaoXeRa_Load(object sender, EventArgs e)
        {
            foreach (LoaiXe loaiXe in cbLoaiXeVao.Items)
            {
                if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeMay.ToUpper()))
                {
                    cbLoaiXeVao.SelectedItem = loaiXe;
                    cbLoaiXeRa.SelectedItem = loaiXe;
                    break;
                }
            }

            var item = _configCamera.ToList().ToList().FirstOrDefault(p => p.ComputerName.Contains(_computerName));
            if (item != null)
            {
                //Camera vao
                int pos = item.CardReader.IndexOf('|');
                if (pos < 0 || (item.CardReader[pos + 1] != '|' && item.CardReader[pos + 2] != '|'))
                    AlertList.Information("Không xác định được thiết bị đọc thẻ. Vui lòng thiết lập cài đặt.");
                else
                {
                    readerDevideVao = item.CardReader.Substring(0, pos);
                    readerDevideRa = item.CardReader.Substring(pos + 3);
                }

                this.axLiveVaoTruoc.IpAddress = item.Server;
                this.axLiveVaoTruoc.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveVaoTruoc.DataPort = System.Convert.ToInt32("5550");
                this.axLiveVaoTruoc.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveVaoTruoc.DisablePWD = true;
                this.axLiveVaoTruoc.DefaultCam = short.Parse(item.Cam1.ToString());
                this.axLiveVaoTruoc.UserName = item.UserID;
                this.axLiveVaoTruoc.Password = item.Password;
                this.axLiveVaoTruoc.PlayX();

                this.axLiveVaoSau.IpAddress = item.Server;
                this.axLiveVaoSau.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveVaoSau.DataPort = System.Convert.ToInt32("5550");
                this.axLiveVaoSau.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveVaoSau.DisablePWD = true;
                this.axLiveVaoSau.DefaultCam = short.Parse(item.Cam2.ToString()); ;
                this.axLiveVaoSau.UserName = item.UserID;
                this.axLiveVaoSau.Password = item.Password;
                this.axLiveVaoSau.PlayX();

                //Camera ra

                this.axLiveRaTruoc.IpAddress = item.Server;
                this.axLiveRaTruoc.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveRaTruoc.DataPort = System.Convert.ToInt32("5550");
                this.axLiveRaTruoc.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveRaTruoc.DisablePWD = true;
                this.axLiveRaTruoc.DefaultCam = short.Parse(item.Cam3.ToString());
                this.axLiveRaTruoc.UserName = item.UserID;
                this.axLiveRaTruoc.Password = item.Password;
                this.axLiveRaTruoc.PlayX();

                this.axLiveRaSau.IpAddress = item.Server;
                this.axLiveRaSau.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveRaSau.DataPort = System.Convert.ToInt32("5550");
                this.axLiveRaSau.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveRaSau.DisablePWD = true;
                this.axLiveRaSau.DefaultCam = short.Parse(item.Cam4.ToString()); ;
                this.axLiveRaSau.UserName = item.UserID;
                this.axLiveRaSau.Password = item.Password;
                this.axLiveRaSau.PlayX();
            }
            else
            {
                AlertList.Warning("Bạn phải thiết lập camera và thiết bị đọc thẻ cho hệ thống trước khi sử dụng.");
            }
            this.Icon = new Icon(this.Icon, this.Icon.Size);
        }

        private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;

            if (null == ex) return;
            MessageBox.Show(ex.Message);
        }

        private void OnKeyPressed(object sender, InputEventArg e)
        {
            if (e.KeyPressEvent.DeviceName.Equals(readerDevideVao))
            {
                isCardReaderVao = true;
                isCardReaderRa = false;
                txtBienSoVao.ReadOnly = true;

            }
            else if (e.KeyPressEvent.DeviceName.Equals(readerDevideRa))
            {
                isCardReaderVao = false;
                isCardReaderRa = true;
                txtBienSoVao.ReadOnly = true;

            }
            else
            {
                isCardReaderVao = false;
                isCardReaderRa = false;
                txtBienSoVao.ReadOnly = false;
            }
        }

        private void LoadLoaiXeVao()
        {
            var loaixe = _loaiXe.ToList().ToList();
            foreach (LoaiXe loai in loaixe)
            {
                //cbLoaiXeRa.Items.Add(loai);
                cbLoaiXeVao.Items.Add(loai);
            }
        }

        private void LoadLoaiXeRa()
        {
            var loaixe = _loaiXe.ToList().ToList();
            foreach (LoaiXe loai in loaixe)
            {
                cbLoaiXeRa.Items.Add(loai);
                //cbLoaiXeVao.Items.Add(loai);
            }
        }

        private void ReadFromCardReader(KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                tempNumber = tempNumber + e.KeyChar;
                readOk = false;
                e.Handled = true;
            }
            else
            {
                if (isCardReaderVao)
                    cardNumberVao = tempNumber;
                if (isCardReaderRa)
                    cardNumberRa = tempNumber;
                tempNumber = string.Empty;
                readOk = true;

            }
        }

        private void frmXeVaoXeRa_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (isCardReaderVao)
            {
                ReadFromCardReader(e);
                if (readOk)
                {
                    cardStatusVao = string.Empty;
                    //timerClock.Enabled = true;
                    txtSoTheVao.Text = cardNumberVao;
                    tempFile = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + _computerName;

                    axLiveVaoTruoc.StartGrapImage(true);
                    countVT = 0;

                    if (_modelV != null && _veTempVao != cardNumberVao)
                    {
                        TiepTucVao();
                    }
                    _veTempVao = cardNumberVao;
                    txtBienSoVao.Focus();
                    txtBienSoVao.SelectAll();
                    autoCountVao = 0;
                }
            }

            if (isCardReaderRa)
            {
                ReadFromCardReader(e);
                if (readOk)
                {
                    cardStatusRa = string.Empty;
                    txtSoTheRa.Text = cardNumberRa;

                    axLiveRaTruoc.StartGrapImage(true);
                    countRT = 0;

                    tempFile = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + _computerName;

                    if (ValidCardRa() && _xe3 != null)
                    {
                        txtBienSoRaVao.Text = _xe3.BienSoXe;
                        lblThoaiGianvao.Text = ((_xe3.NgayVao.HasValue) ? _xe3.NgayVao.Value.ToString("HH:mm:ss dd/MM/yyyy") : "");

                        foreach (LoaiXe itemx in cbLoaiXeRa.Items)
                        {
                            if (itemx.Id == _xe3.LoaiXe.Id)
                            {
                                cbLoaiXeRa.SelectedItem = itemx;
                                break;
                            }

                        }

                        try
                        {
                            picRaVaoTruoc.Load(fileUtil.GenerateLink("ANHVAO", _xe3.ImgVaoTruoc));

                        }
                        catch (Exception)
                        {
                            //MessageBox.Show(ex.Message);
                            picRaVaoTruoc.Image = null;
                        }

                        try
                        {
                            picRaVaoSau.Load(fileUtil.GenerateLink("ANHVAO", _xe3.ImgVaoSau));

                        }
                        catch (Exception)
                        {
                            //MessageBox.Show(ex.Message);
                            picRaVaoSau.Image = null;
                        }

                    }
                    else
                    {
                        txtBienSoRaVao.Text = "";
                        lblThoaiGianvao.Text = "";
                        picRaVaoSau.Image = null;
                        picRaVaoTruoc.Image = null;
                    }


                    if (_modelR != null && _veTempRa != cardNumberRa)
                    {
                        TiepTucRa();
                    }
                    _veTempRa = cardNumberRa;
                    oldCard = txtSoTheRa.Text.Trim();

                    txtBienSoRaRa.Focus();
                    txtBienSoRaRa.SelectAll();
                    autoCountRa = 0;
                }
            }

        }

        #region Insert

        protected void Insert()
        {
            try
            {
                _modelV.BienSoXe = txtBienSoVao.Text.ToUpper();
                _xeT.Create(_modelV);

            }
            catch (Exception ex)
            {
                AlertList.Error("Lỗi phát sinh khi tạo thêm xe vào.");
                //AlertList.Error(ex.ToString());
            }
        }

        #endregion

        private void TiepTucVao()
        {
            if (_modelV != null)
            {
                Insert();
                userType = false;
                _modelV = null;
            }

            txtSoTheVao.Focus();
        }

        private void TiepTucRa()
        {
            Edit();
            _modelR = null;
            txtSoTheRa.Focus();
        }

        #region Edit

        protected void Edit()
        {
            //_xe3 = _xeT.GetByMaxValue("SoVe", "NgayVao", "XeTemp", txtSoVe.Text.Trim());

            try
            {
                _xe.Create(_modelR);

                _xeT = Program.Container.Resolve<IService<XeTemp>>();
                _xe4 = _xeT.GetByMaxValue("SoVe", "NgayVao", "XeTemp", oldCard);
                _xeT.Delete(_xe4);

                //Reset controls
                cardStatusRa = string.Empty;
                txtSoTheRa.Focus();
            }
            catch (Exception)
            {
                AlertList.Error("Có lỗi khi xử lý dữ liệu xe ra.");
            }

        }

        #endregion

        private void frmXeVaoXeRa_KeyDown(object sender, KeyEventArgs e)
        {
            if (!isCardReaderRa && !isCardReaderVao)
            {
                if (e.KeyCode == Keys.F2)
                {
                    //btnDocLai.PerformClick();
                }
                else if (e.KeyCode == Keys.Enter)
                {
                    if (txtBienSoVao.Focus())
                    {
                        if (cardStatusVao.Equals(string.Empty))
                        {
                            TiepTucVao();
                        }
                        else if (!cardStatusVao.Equals(string.Empty))
                        {
                            AlertList.Error(cardStatusVao);
                        }
                    }
                    else if (txtBienSoRaRa.Focus())
                    {
                        if (cardStatusRa.Equals(string.Empty))
                        {
                            TiepTucRa();
                        }
                        else if (!cardStatusRa.Equals(string.Empty))
                        {
                            AlertList.Error(cardStatusRa);
                        }
                    }
                }
                else if (e.KeyCode == Keys.F3)
                {
                    cbLoaiXeVao.SelectedItem = cbLoaiXeVao.Items[1];
                    cbLoaiXeVao.SelectedItem = cbLoaiXeVao.Items[0];
                    //txtSoVe.Text = string.Empty;
                    txtBienSoVao.Focus();
                }
                else if (e.KeyCode == Keys.F4)
                {
                    cbLoaiXeVao.SelectedItem = cbLoaiXeVao.Items[1];
                    txtSoTheVao.Focus();
                }
                else if (e.KeyCode == Keys.F5)
                {
                    cbLoaiXeVao.SelectedItem = cbLoaiXeVao.Items[2];
                    txtSoTheVao.Focus();
                }
            }
        }

        private void frmXeVaoXeRa_FormClosed(object sender, FormClosedEventArgs e)
        {
            _rawinput.KeyPressed -= OnKeyPressed;
            GC.Collect();
        }

        #region Validation
        private bool ValidCardRa()
        {
            isValidCard = true;
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _xeT = Program.Container.Resolve<IService<XeTemp>>();

            _veXe2 = _veXe.Detail(txtSoTheRa.Text.Trim());
            _xe3 = _xeT.GetByMaxValue("SoVe", "NgayVao", "XeTemp", txtSoTheRa.Text.Trim());

            if (txtSoTheRa.Text.Trim().Equals(string.Empty))
            {
                lblStatusRa.Text = @"Đang chờ";
                lblStatusRa.ForeColor = Color.Black;
                isValidCard = false;
            }

            else if (_veXe2 == null)
            {
                lblStatusRa.Text = Constants.VeMessages.VeKhongCoTrongDuLieu;
                cardStatusRa = Constants.VeMessages.VeKhongCoTrongDuLieu;
                lblStatusRa.ForeColor = Color.Red;
                isValidCard = false;
                _xe3 = null;
                AlertList.Error(cardStatusRa);
            }

            else if (_veXe2.Status.Equals(Constants.StatusVeXe.MatVe))
            {
                lblStatusRa.Text = Constants.VeMessages.MatVe;
                cardStatusRa = Constants.VeMessages.MatVe;
                lblStatusRa.ForeColor = Color.Red;
                isValidCard = false;
                _xe3 = null;
                AlertList.Error(cardStatusRa);
            }

            else if (_veXe2.Status.Equals(Constants.StatusVeXe.InActive))
            {
                lblStatusRa.Text = Constants.VeMessages.VeKhongHoatDong;
                cardStatusRa = Constants.VeMessages.VeKhongHoatDong;
                lblStatusRa.ForeColor = Color.Red;
                _xe3 = null;
                isValidCard = false;
                AlertList.Error(cardStatusRa);
            }

            //_xe2 = _xe.ToList().ToList()
            //                .OrderByDescending(b => b.NgayVao)
            //                .FirstOrDefault(p => p.SoVe.Equals(txtSoVe.Text.Trim()));

            else if (_xe3 == null || (_xe3.NgayRa != null && _xe3.ImgRaTruoc != null && _xe3.ImgRaSau != null))
            {
                lblStatusRa.Text = Constants.VeMessages.VeChuaVao;
                cardStatusRa = Constants.VeMessages.VeChuaVao;
                lblStatusRa.ForeColor = Color.Red;
                _xe3 = null;
                isValidCard = false;
                AlertList.Error(cardStatusRa);
            }

            else
            {
                lblStatusRa.Text = Constants.VeMessages.VeHopLe;
                isValidCard = true;
                lblStatusRa.ForeColor = Color.Blue;
            }
            _veXe2 = null;

            return isValidCard;
        }

        private void ValidCardVao()
        {
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _xeT = Program.Container.Resolve<IService<XeTemp>>();

            _veXe2 = _veXe.Detail(txtSoTheVao.Text.Trim());

            _xe2 = _xeT.GetByMaxValue("SoVe", "NgayVao", "XeTemp", txtSoTheVao.Text.Trim());

            if (txtSoTheVao.Text.Trim().Equals(string.Empty))
            {
                lblStatusVao.Text = @"Đang chờ";
                lblStatusVao.ForeColor = Color.Black;
            }

            else if (_veXe2 == null)
            {
                lblStatusVao.Text = Constants.VeMessages.VeKhongCoTrongDuLieu;
                cardStatusVao = Constants.VeMessages.VeKhongCoTrongDuLieu;
                lblStatusVao.ForeColor = Color.Red;
                AlertList.Error(cardStatusVao);
            }

            else if (_veXe2.Status.Equals(Constants.StatusVeXe.MatVe))
            {
                lblStatusVao.Text = Constants.VeMessages.MatVe;
                cardStatusVao = Constants.VeMessages.MatVe;
                lblStatusVao.ForeColor = Color.Red;
                AlertList.Error(cardStatusVao);
            }

            else if (_veXe2.Status.Equals(Constants.StatusVeXe.InActive))
            {
                lblStatusVao.Text = Constants.VeMessages.VeKhongHoatDong;
                cardStatusVao = Constants.VeMessages.VeKhongHoatDong;
                lblStatusVao.ForeColor = Color.Red;
                AlertList.Error(cardStatusVao);
            }

            else if (_xe2 != null && _xe2.NgayRa == null && _xe2.ImgRaTruoc == null && _xe2.ImgRaSau == null)
            {
                lblStatusVao.Text = Constants.VeMessages.VeChuaRa;
                cardStatusVao = Constants.VeMessages.VeChuaRa;
                lblStatusVao.ForeColor = Color.Red;
                AlertList.Error(cardStatusVao);
            }

            else if (cbLoaiXeVao.SelectedItem == null)
            {
                AlertList.Error("Bạn chưa chọn loại xe. Xin vui lòng kiểm tra lại");
                cbLoaiXeVao.Focus();
            }
            else
            {
                lblStatusVao.Text = Constants.VeMessages.VeHopLe;
                lblStatusVao.ForeColor = Color.Blue;

            }
            _veXe2 = null;
            _xe2 = null;
        }

        #endregion

        private void timerVao_Tick(object sender, EventArgs e)
        {
            
            if (autoCountVao == 100)
            {
                if (_modelV != null)
                {
                    TiepTucVao();
                }
                _veTempVao = cardNumberVao;
                autoCountVao = 0;
                GC.Collect();
            }
            else
            {
                autoCountVao++;
            }
        }

        private void timerRa_Tick(object sender, EventArgs e)
        {

            if (autoCountRa == 100)
            {
                if (_modelR != null)
                {
                    TiepTucRa();
                }
                _veTempRa = cardNumberRa;
                autoCountRa = 0;
                GC.Collect();
            }
            else
            {
                autoCountRa++;
            }
        }

        private void cbLoaiXeVao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((LoaiXe)cbLoaiXeVao.SelectedItem).Ten.ToUpper().Equals(Constants.Xe.XeDap.ToUpper()))
            {
                rand = new Random();
                do
                {
                    _veXeDap = rand.Next(100, 999).ToString();
                } while (_veXeDap.Equals(txtBienSoVao.Text));
                //if (!string.IsNullOrEmpty(txtSoVe.Text.Trim()))
                //{
                //    txtBiensovao.Text = txtSoVe.Text.Trim().Substring(6, 4);
                //}
                txtBienSoVao.Text = _veXeDap;

            }
        }

    }
}
